var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var express_logger = require('./common/exress_logger').express_logger;
var vertoken = require('./common/token');
const httpresult = require("./common/response");
const mysql_query = require('./common/mysql');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(express_logger);
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

let router = express.Router();
router.use(function (req, res, next) {
  if (req.url === "/user/login" || req.url === "/user/register") {
    return next();
  }
  var token = req.headers['x-access-token'];
  if (token === undefined || token === "") {
    return res.send(httpresult.trans_error("LOGIN_EXPIRE", "请重新登陆"));
  }
  vertoken.ver_token(token).then(async (data) => {
    req.user_id = data.user_id;
    req.user_role = data.user_role;
    let [err, users] = await mysql_query("select * from user where user_id = ?", req.user_id);
    if (err) {
      return res.send(httpresult.sys_error(err));
    }
    if (users.length == 0) {
      return res.send(httpresult.trans_error("LOGIN_EXPIRE", "请重新登陆"));
    }
    return next();
  }).catch((error) => {
    return res.send(httpresult.trans_error("LOGIN_EXPIRE", "请重新登陆"));
  });

});
router.use('/', require('./routes/index'));
router.use('/user', require('./routes/user'));
router.use('/course', require('./routes/course'));
router.use('/user_course', require('./routes/user_course'));
router.use('/chapter', require('./routes/chapter'));
router.use('/bank', require('./routes/bank'));
router.use('/question', require('./routes/question'));
router.use('/bank_question', require('./routes/bank_question'));
router.use('/study_record', require('./routes/study_record'));
router.use('/datafile', require('./routes/datafile'));
// catch 404 and forward to error handler
router.use(function(req, res, next) {
  next(createError(404));
});

// error handler
router.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
app.use('/api', router);
module.exports = app;
